<template>
  <ry-modal
    :title="isEdit ? '编辑暂存记录' : '新增暂存记录'"
    v-model="visible"
    destroyOnClose
    :confirmLoading="confirmLoading"
    :ryfooter="null"
    width="1000px"
  >
    <div class="table-container freeze-record-modal-body">
      <a-form-model
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="modelConfig.labelCol"
        :wrapper-col="modelConfig.wrapperCol"
        class="freeze-record-form"
      >
        <a-row :gutter="24">
          <!-- ==================== 绑定细胞 ==================== -->
          <a-col
            :span="24"
            style="font-weight:600;margin-bottom:10px;margin-left:20px"
          >
            <span style="background-color:#3acaca;margin-right:4px">&nbsp;</span>绑定细胞
          </a-col>

          <!-- 细胞编号（选择 + 隐藏输入用于校验/收集） -->
          <a-col :span="12">
            <a-form-model-item label="细胞编号" prop="cellCode">
              <!-- 隐藏控件：用于收集 cellCode -->
              <a-input v-model="formData.cellCode" style="display:none;" />
              <div class="bind-project-tags">
                <template v-if="formData.cellCode">
                  <span style="color: #00A0E9">{{ formData.cellCode }}</span>
                </template>
                <template v-else>
                  <span class="bind-project-placeholder">未选择</span>
                </template>
                <!-- 仅新增时可选择 -->
                <a-button
                  v-if="!isEdit"
                  size="small"
                  style="margin-left:8px;"
                  @click="openCellModal"
                >选择</a-button>
              </div>
            </a-form-model-item>
          </a-col>

          <!-- 项目名称（Tag 列，仿采样） -->
          <a-col :span="12">
            <a-form-model-item label="项目名称">
              <div class="bind-project-tags">
                <template v-if="applyProjectTagList.length">
                  <a-tag
                    v-for="tag in applyProjectTagList"
                    :key="tag"
                    color="blue"
                  >
                    {{ tag }}
                  </a-tag>
                </template>
                <template v-else>
                  <span class="bind-project-placeholder">--</span>
                </template>
              </div>
            </a-form-model-item>
          </a-col>

          <!-- 客户姓名 -->
          <a-col :span="12">
            <a-form-model-item label="客户姓名">
              <a-input
                v-model="formData.nickname"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <!-- 客户手机号 -->
          <a-col :span="12">
            <a-form-model-item label="联系方式">
              <a-input
                v-model="formData.phone"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="细胞管数(原)">
              <a-input
                v-model="formData.originalCellNum"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="细胞管数(余)">
              <a-input
                v-model="formData.cellNum"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="细胞数量">
              <a-input
                v-model="formData.quantity"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <!-- ==================== 冻存信息 ==================== -->
          <a-col
            :span="24"
            style="font-weight:600;margin-bottom:10px;margin-left:20px;margin-top:4px"
          >
            <span style="background-color:#3acaca;margin-right:4px">&nbsp;</span>暂存信息
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="液氮罐编号" prop="liquidNitrogenTank">
              <a-input v-model="formData.liquidNitrogenTank" placeholder="请输入液氮罐编号" />
            </a-form-model-item>
          </a-col>

          <!-- 冻存时间：新增显示，编辑隐藏 -->
          <a-col :span="12">
            <a-form-model-item label="暂存时间" prop="freezeTime">
              <a-date-picker
                v-model="formData.freezeTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                style="width:100%"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="处理实验室" prop="processLab">
              <a-input v-model="formData.processLab" placeholder="请输入处理实验室" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="区" prop="area">
              <a-input v-model="formData.area" placeholder="请输入区" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="架号" prop="rack">
              <a-input v-model="formData.rack" placeholder="请输入架号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="层号" prop="level">
              <a-input v-model="formData.level" placeholder="请输入层号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="盒号" prop="box">
              <a-input v-model="formData.box" placeholder="请输入盒号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="暂存方法" prop="freezeMethod">
              <a-input v-model="formData.freezeMethod" placeholder="请输入暂存方法" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="存储规格" prop="containerType">
              <a-input v-model="formData.containerType" placeholder="请输入容器类型" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="容器数量" prop="containerCount">
              <a-input v-model="formData.containerCount" placeholder="容器数量" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="细胞数" prop="cellCount">
              <a-input
                v-model="formData.cellCount"
                placeholder="细胞数"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="细胞活性(%)" prop="cellActivity">
              <a-input-number
                v-model="formData.cellActivity"
                :min="0"
                :max="100"
                style="width:100%"
                placeholder="活性百分比"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="存储温度" prop="storageTemperature">
              <a-input v-model="formData.storageTemperature" placeholder="例如 -196℃" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="到期时间" prop="expireTime">
              <a-date-picker
                v-model="formData.expireTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                style="width:100%"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="处理人" prop="processUser">
              <a-input v-model="formData.processUser" placeholder="请输入处理人" />
            </a-form-model-item>
          </a-col>

        </a-row>

        <!-- 按钮 -->
        <a-form-model-item :wrapper-col="{ span: 24 }" class="form-btn-row">
          <div class="form-btn-group">
            <a-button type="primary" :loading="confirmLoading" @click="handleOk">提交</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>

    <!-- 细胞选择弹框 -->
    <CellSelectModal ref="cellSelectModal" @cell="onCellSelected" />
  </ry-modal>
</template>

<script>
import { freezeRecord } from '@/apilist/permission'
import CellSelectModal from './CellSelectModal.vue' // 路径按实际

export default {
  name: 'FreezeRecordModal',
  components: { CellSelectModal },
  data() {
    return {
      visible: false,
      isEdit: false,
      confirmLoading: false,
      formData: this.getEmptyForm(),
      rules: {
        freezeTime:  [{ required: true, message: '请选择冻存时间', trigger: 'change' }],
        liquidNitrogenTank:  [{ required: true, message: '请输入液氮罐编号', trigger: 'blur' }],
        processLab:     [{ required: true, message: '请输入处理实验室', trigger: 'blur' }],
        processUser:    [{ required: true, message: '请输入处理人', trigger: 'blur' }],
        containerCount: [{ required: true, message: '请输入容器数量', trigger: 'blur' }],
        cellCount:      [{ required: true, message: '请输入细胞数', trigger: 'blur' }],
        cellCode:       [{ required: true, message: '请选择细胞', trigger: 'change' }]
      },
      modelConfig: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      }
    }
  },

  computed: {
    applyProjectTagList() {
      const codes = this.formData.applyProject || ''
      if (!codes) return []
      return codes
        .split(',')
        .map(c => c.trim())
        .filter(Boolean)
        .map(c => this.$getDictName('APPLY_PROJECT', c))
    }
  },

  methods: {
    getEmptyForm() {
      return {
        id: null,
        freezeTime: null,
        cellCode: '',
        nickname: '',
        phone: '',
        cellNum: '',
        originalCellNum: '',
        quantity: '',
        applyProject: '',
        processLab: '',
        freezeMethod: '',
        containerType: '',
        containerCount: '',
        cellCount: '',
        cellActivity: null,
        storageTemperature: '-196℃',
        expireTime: null,
        processUser: '',
        remark: ''
      }
    },

    open(record) {
      this.visible = true

      if (record && record.id) {
        this.isEdit = true
        this.confirmLoading = true
        this.formData = this.getEmptyForm()

        window.$axios
          .get(`${freezeRecord.byId}/${record.id}`)
          .then(res => {
            const d = res && res.data && (res.data.data || res.data) ? (res.data.data || res.data) : {}
            const projCodes = d.applyProject || record.applyProject || ''
            this.formData = {
              ...this.getEmptyForm(),
              id: d.id || record.id,
              area: d.area || '',
              rack: d.rack || '',
              level: d.level || '',
              box: d.box || '',
              liquidNitrogenTank: d.liquidNitrogenTank || '',
              freezeTime: d.freezeTime || null,
              processLab: d.processLab || '',
              freezeMethod: d.freezeMethod || '',
              containerType: d.containerType || '',
              containerCount: d.containerCount != null ? d.containerCount : '',
              cellCount: d.cellCount != null ? d.cellCount : '',
              cellActivity: d.cellActivity,
              storageTemperature: d.storageTemperature || '-196℃',
              expireTime: d.expireTime || null,
              processUser: d.processUser || '',
              remark: d.remark || '',
              cellCode: d.cellCode || (record.cellCode || ''),
              nickname:
                d.nickname ||
                (d.businessAccount ? d.businessAccount.nickname : '') ||
                (record.nickname || ''),
              phone:
                d.phone ||
                (d.businessAccount ? d.businessAccount.phone : '') ||
                (record.phone || ''),
              cellNum:
                d.cellNum ||
                (d.businessAccount ? d.businessAccount.cellNum : '') ||
                (record.cellNum || ''),
              originalCellNum:
                d.originalCellNum ||
                (d.businessAccount ? d.businessAccount.originalCellNum : '') ||
                (record.originalCellNum || ''),
              quantity:
                d.quantity ||
                (d.businessAccount ? d.businessAccount.quantity : '') ||
                (record.quantity || ''),
              applyProject: projCodes
            }
          })
          .catch(() => {
            this.$message.error('加载详情失败')
            this.formData = {
              ...this.getEmptyForm(),
              ...record,
              cellCode: record.cellCode || '',
              nickname: record.nickname || '',
              phone: record.phone || '',
              cellNum: record.cellNum || '',
              originalCellNum: record.originalCellNum || '',
              quantity: record.quantity || '',
              applyProject: record.applyProject || ''
            }
          })
          .finally(() => {
            this.confirmLoading = false
          })

      } else {
        this.isEdit = false
        this.resetForm()
      }
    },

    openCellModal() {
      this.$refs.cellSelectModal.open('2')
    },

    /** 选中细胞：更新 + 触发校验，确保提交时带上 cellCode */
    onCellSelected(cell) {
      if (!cell) return
      console.log('onCellSelected', cell)
      this.formData.cellId = cell.id
      this.formData.cellCode = cell.cellCode || ''
      this.formData.cellNum = cell.cellNum || ''
      this.formData.originalCellNum = cell.originalCellNum || ''
      this.formData.quantity = cell.quantity || ''
      this.formData.nickname =
        cell.nickname ||
        cell.customerName ||
        (cell.businessAccount ? cell.businessAccount.nickname : '') ||
        ''
      this.formData.phone =
        cell.phone ||
        cell.customerPhone ||
        (cell.businessAccount ? cell.businessAccount.phone : '') ||
        ''
      this.formData.applyProject = cell.applyProject || ''
      // 触发校验（因为我们用的是隐藏控件）
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.validateField('cellCode')
      })
    },

    handleOk() {
      if (this.confirmLoading) {
        this.$message.warning('请稍候，正在加载详情…')
        return
      }

      // 手动判断，防止用户没选细胞
      if (!this.formData.cellCode) {
        this.$message.error('请选择细胞')
        return
      }

      this.$refs.formRef.validate(valid => {
        if (!valid) {
          this.$message.warning('请检查表单填写')
          return
        }

        const api = this.isEdit ? freezeRecord.update : freezeRecord.insert
        const dataToSubmit = this.buildSubmitData()

        this.confirmLoading = true
        window.$axios.post(api, dataToSubmit)
          .then(() => {
            this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
            this.$emit('ModalOk')
            this.visible = false
          })
          .catch(() => {
            this.$message.error('提交失败')
          })
          .finally(() => {
            this.confirmLoading = false
          })
      })
    },

    buildSubmitData() {
      const payload = {
        id: this.formData.id,
        area: this.formData.area,
        rack: this.formData.rack,
        level: this.formData.level,
        box: this.formData.box,
        cellId: this.formData.cellId,
        liquidNitrogenTank: this.formData.liquidNitrogenTank,
        cellCode: this.formData.cellCode, // <== 必传
        processLab: this.formData.processLab,
        freezeMethod: this.formData.freezeMethod,
        containerType: this.formData.containerType,
        containerCount: this.formData.containerCount,
        cellCount: this.formData.cellCount,
        cellActivity: this.formData.cellActivity,
        storageTemperature: this.formData.storageTemperature,
        expireTime: this.normalizeTime(this.formData.expireTime),
        processUser: this.formData.processUser,
        remark: this.formData.remark,
        nickname: this.formData.nickname,
        phone: this.formData.phone,
        cellNum: this.formData.cellNum,
        originalCellNum: this.formData.originalCellNum,
        quantity: this.formData.quantity,
        applyProject: this.formData.applyProject
      }
      if (!this.isEdit) {
        payload.freezeTime = this.normalizeTime(this.formData.freezeTime)
      }
      return payload
    },

    normalizeTime(val) {
      if (!val) return null
      if (val && typeof val === 'object' && typeof val.format === 'function') {
        return val.format('YYYY-MM-DD HH:mm:ss')
      }
      if (val instanceof Date) {
        return this.formatDate(val)
      }
      if (typeof val === 'string') {
        return val
      }
      return null
    },

    formatDate(date) {
      const d = new Date(date)
      if (isNaN(d.getTime())) return null
      const pad = n => (n < 10 ? '0' + n : n)
      return (
        d.getFullYear() + '-' +
        pad(d.getMonth() + 1) + '-' +
        pad(d.getDate()) + ' ' +
        pad(d.getHours()) + ':' +
        pad(d.getMinutes()) + ':' +
        pad(d.getSeconds())
      )
    },

    handleCancel() {
      this.visible = false
    },

    resetForm() {
      this.formData = this.getEmptyForm()
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    }
  }
}
</script>

<style scoped>
.freeze-record-modal-body { padding: 0 8px; }
.freeze-record-form .ant-form-item { margin-bottom: 16px; }
.form-btn-row { margin-top: 8px; }
.form-btn-group { display: flex; justify-content: center; gap: 24px; }
.table-container { padding: 0; }
.bind-project-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  min-height: 32px;
  gap: 4px;
}
.bind-project-placeholder {
  color: #999;
}
</style>
